{% extends "base.html" %}

{% block title %}医生端 - 慢性病风险预测与智能干预系统{% endblock %}

{% block content %}
<!-- 医生端标题 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center me-3" style="width: 60px; height: 60px;">
                        <i class="fas fa-user-md fa-lg"></i>
                    </div>
                    <div>
                        <h2 class="mb-1">医生端管理平台</h2>
                        <p class="text-muted mb-0">群体健康管理 · 高危人群筛查 · 干预效果评估</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 统计概览 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-primary mb-2">
                    <i class="fas fa-users fa-2x"></i>
                </div>
                <h4 class="mb-1" id="totalPatients">1,234</h4>
                <p class="text-muted mb-0">总患者数</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-warning mb-2">
                    <i class="fas fa-exclamation-triangle fa-2x"></i>
                </div>
                <h4 class="mb-1" id="highRiskPatients">156</h4>
                <p class="text-muted mb-0">高风险患者</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-success mb-2">
                    <i class="fas fa-chart-line fa-2x"></i>
                </div>
                <h4 class="mb-1" id="improvedPatients">89</h4>
                <p class="text-muted mb-0">改善患者</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card text-center">
            <div class="card-body">
                <div class="text-info mb-2">
                    <i class="fas fa-percentage fa-2x"></i>
                </div>
                <h4 class="mb-1" id="predictionAccuracy">87.3%</h4>
                <p class="text-muted mb-0">预测准确率</p>
            </div>
        </div>
    </div>
</div>

<!-- 主要功能区域 -->
<div class="row">
    <!-- 批量数据上传 -->
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-upload me-2"></i>
                    批量数据上传
                </h5>
            </div>
            <div class="card-body">
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="dataFile" class="form-label">选择数据文件</label>
                        <input type="file" class="form-control" id="dataFile" accept=".csv,.xlsx" required>
                        <div class="form-text">支持CSV和Excel格式，包含患者基础信息和生理指标</div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="includePrediction" checked>
                            <label class="form-check-label" for="includePrediction">
                                包含风险预测分析
                            </label>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-upload me-2"></i>
                        上传并分析
                    </button>
                </form>
                
                <!-- 上传结果 -->
                <div id="uploadResult" class="mt-3" style="display: none;">
                    <div class="alert alert-success">
                        <h6>上传成功！</h6>
                        <div id="uploadStats"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 风险分布分析 -->
    <div class="col-lg-6 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-chart-pie me-2"></i>
                    风险分布分析
                </h5>
            </div>
            <div class="card-body">
                <div id="riskDistributionChart" class="chart-container"></div>
            </div>
        </div>
    </div>
</div>

<!-- 图表分析区域 -->
<div class="row">
    <!-- 风险因素分析 -->
    <div class="col-lg-8 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-chart-bar me-2"></i>
                    风险因素分析
                </h5>
            </div>
            <div class="card-body">
                <div id="riskFactorsChart" class="chart-container"></div>
            </div>
        </div>
    </div>
    
    <!-- 趋势分析 -->
    <div class="col-lg-4 mb-4">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-trending-up me-2"></i>
                    趋势分析
                </h5>
            </div>
            <div class="card-body">
                <div id="trendChart" class="chart-container"></div>
            </div>
        </div>
    </div>
</div>

<!-- 患者列表 -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2"></i>
                    患者风险列表
                </h5>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="filterPatients('all')">全部</button>
                    <button type="button" class="btn btn-outline-warning btn-sm" onclick="filterPatients('high')">高风险</button>
                    <button type="button" class="btn btn-outline-info btn-sm" onclick="filterPatients('medium')">中风险</button>
                    <button type="button" class="btn btn-outline-success btn-sm" onclick="filterPatients('low')">低风险</button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover" id="patientsTable">
                        <thead>
                            <tr>
                                <th>患者ID</th>
                                <th>年龄</th>
                                <th>性别</th>
                                <th>BMI</th>
                                <th>血压</th>
                                <th>血糖</th>
                                <th>综合风险</th>
                                <th>风险等级</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="patientsTableBody">
                            <!-- 患者数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 初始化图表
    initRiskDistributionChart();
    initRiskFactorsChart();
    initTrendChart();
    loadPatientsData();
    
    // 文件上传处理
    $('#uploadForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData();
        const fileInput = document.getElementById('dataFile');
        const includePrediction = document.getElementById('includePrediction').checked;
        
        if (fileInput.files.length === 0) {
            showAlert('请选择要上传的文件', 'warning');
            return;
        }
        
        formData.append('file', fileInput.files[0]);
        formData.append('include_prediction', includePrediction);
        
        // 显示上传进度
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin me-2"></i>上传中...').prop('disabled', true);
        
        $.ajax({
            url: '/api/upload_data',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    displayUploadResult(response);
                    showAlert('数据上传成功！', 'success');
                } else {
                    showAlert('上传失败：' + response.error, 'danger');
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON ? xhr.responseJSON.error : '网络错误';
                showAlert('上传失败：' + errorMsg, 'danger');
            },
            complete: function() {
                submitBtn.html(originalText).prop('disabled', false);
            }
        });
    });
    
    // 显示上传结果
    function displayUploadResult(response) {
        const statsHtml = `
            <p><strong>处理记录数：</strong>${response.total_records}</p>
            <p><strong>风险分布：</strong></p>
            <ul>
                <li>高风险：${response.risk_distribution.high_risk} 人</li>
                <li>中风险：${response.risk_distribution.medium_risk} 人</li>
                <li>低风险：${response.risk_distribution.low_risk} 人</li>
            </ul>
        `;
        
        $('#uploadStats').html(statsHtml);
        $('#uploadResult').show();
        
        // 更新统计数字
        updateStatistics(response);
        
        // 刷新图表
        setTimeout(() => {
            initRiskDistributionChart();
            loadPatientsData();
        }, 1000);
    }
    
    // 更新统计数字
    function updateStatistics(response) {
        const total = response.total_records;
        const highRisk = response.risk_distribution.high_risk;
        const mediumRisk = response.risk_distribution.medium_risk;
        const lowRisk = response.risk_distribution.low_risk;
        
        // 动画更新数字
        animateNumber('#totalPatients', parseInt($('#totalPatients').text().replace(',', '')) + total);
        animateNumber('#highRiskPatients', parseInt($('#highRiskPatients').text()) + highRisk);
        animateNumber('#improvedPatients', parseInt($('#improvedPatients').text()) + Math.floor(mediumRisk * 0.3));
    }
    
    // 数字动画
    function animateNumber(selector, targetValue) {
        const element = $(selector);
        const currentValue = parseInt(element.text().replace(',', ''));
        const increment = (targetValue - currentValue) / 20;
        let current = currentValue;
        
        const timer = setInterval(() => {
            current += increment;
            if ((increment > 0 && current >= targetValue) || (increment < 0 && current <= targetValue)) {
                current = targetValue;
                clearInterval(timer);
            }
            element.text(Math.floor(current).toLocaleString());
        }, 50);
    }
    
    // 初始化风险分布图表
    function initRiskDistributionChart() {
        const chart = echarts.init(document.getElementById('riskDistributionChart'));
        
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '风险分布',
                    type: 'pie',
                    radius: '50%',
                    data: [
                        { value: 156, name: '高风险', itemStyle: { color: '#e74c3c' } },
                        { value: 234, name: '中风险', itemStyle: { color: '#f39c12' } },
                        { value: 844, name: '低风险', itemStyle: { color: '#27ae60' } }
                    ],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        
        chart.setOption(option);
        
        // 响应式调整
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 初始化风险因素图表
    function initRiskFactorsChart() {
        const chart = echarts.init(document.getElementById('riskFactorsChart'));
        
        const option = {
            title: {
                text: '主要风险因素影响权重',
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                boundaryGap: [0, 0.01]
            },
            yAxis: {
                type: 'category',
                data: ['血糖', '收缩压', 'BMI', '吸烟', '家族史', '年龄', '运动频率', '饮食偏好']
            },
            series: [
                {
                    name: '影响权重',
                    type: 'bar',
                    data: [0.15, 0.12, 0.10, 0.09, 0.08, 0.07, -0.05, 0.06],
                    itemStyle: {
                        color: function(params) {
                            return params.value > 0 ? '#e74c3c' : '#27ae60';
                        }
                    }
                }
            ]
        };
        
        chart.setOption(option);
        
        // 响应式调整
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 初始化趋势图表
    function initTrendChart() {
        const chart = echarts.init(document.getElementById('trendChart'));
        
        const option = {
            title: {
                text: '月度趋势',
                left: 'center',
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: ['1月', '2月', '3月', '4月', '5月', '6月']
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '高风险患者',
                    type: 'line',
                    data: [120, 132, 145, 156, 148, 156],
                    itemStyle: {
                        color: '#e74c3c'
                    }
                }
            ]
        };
        
        chart.setOption(option);
        
        // 响应式调整
        window.addEventListener('resize', function() {
            chart.resize();
        });
    }
    
    // 加载患者数据
    function loadPatientsData() {
        // 模拟患者数据
        const patientsData = [
            { id: 'P001', age: 45, gender: '男', bmi: 26.5, bp: '135/85', glucose: 105, risk: 0.65, level: 'high' },
            { id: 'P002', age: 38, gender: '女', bmi: 22.1, bp: '118/78', glucose: 95, risk: 0.25, level: 'low' },
            { id: 'P003', age: 52, gender: '男', bmi: 28.3, bp: '142/88', glucose: 110, risk: 0.72, level: 'high' },
            { id: 'P004', age: 41, gender: '女', bmi: 24.8, bp: '125/82', glucose: 98, risk: 0.45, level: 'medium' },
            { id: 'P005', age: 35, gender: '男', bmi: 23.2, bp: '115/75', glucose: 92, risk: 0.18, level: 'low' }
        ];
        
        displayPatientsTable(patientsData);
    }
    
    // 显示患者表格
    function displayPatientsTable(patients) {
        const tbody = $('#patientsTableBody');
        tbody.empty();
        
        patients.forEach(patient => {
            const row = `
                <tr>
                    <td>${patient.id}</td>
                    <td>${patient.age}</td>
                    <td>${patient.gender}</td>
                    <td>${patient.bmi}</td>
                    <td>${patient.bp}</td>
                    <td>${patient.glucose}</td>
                    <td>${(patient.risk * 100).toFixed(1)}%</td>
                    <td>${formatRiskLevel(patient.level)}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="viewPatientDetail('${patient.id}')">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-success" onclick="generateReport('${patient.id}')">
                            <i class="fas fa-file-pdf"></i>
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }
    
    // 患者筛选
    window.filterPatients = function(level) {
        // 这里可以实现患者筛选逻辑
        showAlert(`已筛选${level === 'all' ? '全部' : level === 'high' ? '高风险' : level === 'medium' ? '中风险' : '低风险'}患者`, 'info');
    };
    
    // 查看患者详情
    window.viewPatientDetail = function(patientId) {
        showAlert(`查看患者 ${patientId} 的详细信息`, 'info');
    };
    
    // 生成报告
    window.generateReport = function(patientId) {
        showAlert(`正在生成患者 ${patientId} 的风险评估报告...`, 'info');
    };
});
</script>
{% endblock %}
